﻿var context;
var web;
var list;
var listItems;
var listName = "Facts";

$(document).ready(function () {
    // Get context and web
    context = new SP.ClientContext.get_current();
    web = context.get_web();

    // Get silly fact
    getSillyFact();
});

function getSillyFact() {
    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml("<View><RowLimit>100</RowLimit></View>");

    list = web.get_lists().getByTitle(listName);
    listItems = list.getItems(camlQuery);

    context.load(list);
    context.load(listItems);

    context.executeQueryAsync(onSuccessGetSillyFacts, onFailedAction);
}

function onSuccessGetSillyFacts(sender, args) {
    var i = listItems.get_count();
    rnd = Math.floor((Math.random() * i));

    var fact = listItems.get_item(rnd);

    document.getElementById("SillyFactsPanel").title = "There are " + i + " Silly Facts!";
    document.getElementById("SillyFactsPanel").innerHTML = fact.get_item("Title");
}

function onFailedAction(sender, args) {
    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}